// node version >= 14.14.0
const FS = require("fs");
const repl = require('repl');
let assetsPaths = ["../assets"]; // 图片文件夹
let targetPaths = ["../components","../views","../sass","../request","../router","../store","../App.vue","../main.js"]; // 要检查的文件夹
let imgTypes = ["jpg","jpeg","png","gif","webp"] // 清除的图片类型
let nonUseCount = 0;
let type = "";

console.log("查看：.check, 删除：.delete, 退出：.exit")
let replServer = repl.start(">")
replServer.defineCommand('check', {
  help: '查看没有被使用的图片',
  action() {
    this.clearBufferedCommand();
    type = "check";
    run();
    this.displayPrompt();
  }
});
replServer.defineCommand('delete', {
  help: '删除没有被使用的图片',
  action() {
    this.clearBufferedCommand();
    type = "delete";
    run();
    this.displayPrompt();
  }
});
// 拿到图片，遍历目标文件夹
function run() {
  console.log("\x1B[32m","开始运行...");
  nonUseCount = 0;
  for (let assetsPath of assetsPaths) {
    // 先拿到图片
    readdir(assetsPath,"",assetsFilePath=>{
      let res = assetsFilePath.match(/\.\w+$/);
      res = res ? res[0] : null;
      // 图片的时候才处理
      if (res && imgTypes.includes(res.substr(1))) {
        let isUsing = false;
        for (let dir of targetPaths) {
          if (FS.statSync(dir).isFile()) {
            if(!isUsing) isUsing = includesImg(dir,assetsFilePath);
          } else {
             // 遍历目标文件夹
            readdir(dir,"",filePath=>{
              if (!isUsing) {
                isUsing = includesImg(filePath,assetsFilePath);
              }
            })
          }
        }
        if (!isUsing) {
          nonUseCount++;
          if (type == "check") {
            console.log('\x1B[37m',`${assetsFilePath}`,'\x1B[31m',"没有在使用")
          } else if (type == "delete") {
            FS.rmSync(assetsFilePath)
            console.log('\x1B[31m','delete','\x1B[37m',assetsFilePath);
          }
        }
      }
    })
  }
  if (type == "check") {
    console.log('\x1B[37m',"没有使用过的图片数量：",'\x1B[31m',''+nonUseCount,"\x1B[37m")
  } else if (type == "delete") {
    console.log('\x1B[37m',"已删除图片数量：",'\x1B[31m',''+nonUseCount,"\x1B[37m")
  }
}



/**
 *读取文件夹
 *
 * @param {String} dir 要读取的目录
 * @param {String} path 当前路径
 * @param {Function} handleFile 处理文件
 */
function readdir(dir,path,handleFile) {
  if (path.length!=0) { // 后面开始遍历文件夹时
    path = `${path}/${dir}`
  } else { // 刚开始时，path=""
    path = dir;
  }
  let result = FS.readdirSync(path);
  result.forEach(item=>{
    let l_path = `${path}/${item}`;
    if (FS.statSync(l_path).isDirectory()) {
      readdir(item,path,handleFile)
    } else {
      handleFile && handleFile(l_path)
    }
  })
  // ../assets/ -> ../assets
  path = path.split("/");
  path.pop(); 
  path = path.join('/')
}
function includesImg(filePath,assetsFilePath) {
  return FS.readFileSync(filePath).toString().includes(assetsFilePath.substr(3));
}